// utils/storage.js - 本地存储工具函数

// 存储键名常量
const STORAGE_KEYS = {
  TOKEN: 'task_platform_token',
  USER_INFO: 'task_platform_user_info',
  USER_POINTS: 'task_platform_points',
  LOGIN_TYPE: 'task_platform_login_type',
  SEARCH_HISTORY: 'task_platform_search_history',
  VIEWED_TASKS: 'task_platform_viewed_tasks',
  APP_SETTINGS: 'task_platform_settings',
  TASK_STATUS_MAP: 'task_platform_task_status_map'
};

// 存储数据
export const setItem = (key, value) => {
  try {
    // 对于复杂对象，进行JSON序列化
    const storageValue = typeof value === 'object' ? JSON.stringify(value) : value;
    uni.setStorageSync(key, storageValue);
    return true;
  } catch (error) {
    console.error('存储数据失败:', error);
    return false;
  }
};

// 获取数据
export const getItem = (key, defaultValue = null) => {
  try {
    const value = uni.getStorageSync(key);
    if (value === undefined || value === null) {
      return defaultValue;
    }
    
    // 尝试解析JSON，失败则返回原始值
    try {
      return JSON.parse(value);
    } catch {
      return value;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    return defaultValue;
  }
};

// 删除数据
export const removeItem = (key) => {
  try {
    uni.removeStorageSync(key);
    return true;
  } catch (error) {
    console.error('删除数据失败:', error);
    return false;
  }
};

// 清除所有数据
export const clearAll = () => {
  try {
    uni.clearStorageSync();
    return true;
  } catch (error) {
    console.error('清除数据失败:', error);
    return false;
  }
};

// 存储Token
export const setToken = (token) => {
  return setItem(STORAGE_KEYS.TOKEN, token);
};

// 获取Token
export const getToken = () => {
  return getItem(STORAGE_KEYS.TOKEN, null);
};

// 清除Token
export const removeToken = () => {
  return removeItem(STORAGE_KEYS.TOKEN);
};

// 存储用户信息
export const setUserInfo = (userInfo) => {
  return setItem(STORAGE_KEYS.USER_INFO, userInfo);
};

// 获取用户信息
export const getUserInfo = () => {
  return getItem(STORAGE_KEYS.USER_INFO, null);
};

// 清除用户信息
export const removeUserInfo = () => {
  return removeItem(STORAGE_KEYS.USER_INFO);
};

// 存储积分
export const setPoints = (points) => {
  return setItem(STORAGE_KEYS.USER_POINTS, points);
};

// 获取积分
export const getPoints = () => {
  return getItem(STORAGE_KEYS.USER_POINTS, 0);
};

// 存储任务状态
export const setTaskStatus = (taskId, status) => {
  const taskStatusMap = getItem(STORAGE_KEYS.TASK_STATUS_MAP) || {};
  taskStatusMap[taskId] = status;
  return setItem(STORAGE_KEYS.TASK_STATUS_MAP, taskStatusMap);
};

// 获取任务状态
export const getTaskStatus = (taskId) => {
  const taskStatusMap = getItem(STORAGE_KEYS.TASK_STATUS_MAP) || {};
  return taskStatusMap[taskId] || null;
};

// 设置登录类型
export const setLoginType = (loginType) => {
  return setItem(STORAGE_KEYS.LOGIN_TYPE, loginType);
};

// 获取登录类型
export const getLoginType = () => {
  return getItem(STORAGE_KEYS.LOGIN_TYPE, null);
};

// 保存搜索历史
export const saveSearchHistory = (keyword, maxLength = 10) => {
  try {
    let history = getItem(STORAGE_KEYS.SEARCH_HISTORY, []);
    
    // 去重，删除已存在的关键词
    history = history.filter(item => item !== keyword);
    
    // 添加到开头
    history.unshift(keyword);
    
    // 限制长度
    if (history.length > maxLength) {
      history = history.slice(0, maxLength);
    }
    
    return setItem(STORAGE_KEYS.SEARCH_HISTORY, history);
  } catch (error) {
    console.error('保存搜索历史失败:', error);
    return false;
  }
};

// 获取搜索历史
export const getSearchHistory = () => {
  return getItem(STORAGE_KEYS.SEARCH_HISTORY, []);
};

// 清除搜索历史
export const clearSearchHistory = () => {
  return removeItem(STORAGE_KEYS.SEARCH_HISTORY);
};

// 保存浏览过的任务ID
export const saveViewedTask = (taskId, maxLength = 20) => {
  try {
    let viewedTasks = getItem(STORAGE_KEYS.VIEWED_TASKS, []);
    
    // 去重
    viewedTasks = viewedTasks.filter(id => id !== taskId);
    
    // 添加到开头
    viewedTasks.unshift(taskId);
    
    // 限制长度
    if (viewedTasks.length > maxLength) {
      viewedTasks = viewedTasks.slice(0, maxLength);
    }
    
    return setItem(STORAGE_KEYS.VIEWED_TASKS, viewedTasks);
  } catch (error) {
    console.error('保存浏览记录失败:', error);
    return false;
  }
};

// 获取浏览过的任务ID列表
export const getViewedTasks = () => {
  return getItem(STORAGE_KEYS.VIEWED_TASKS, []);
};

// 退出登录，清除所有用户相关数据
export const logout = () => {
  try {
    removeToken();
    removeUserInfo();
    setPoints(0);
    removeItem(STORAGE_KEYS.LOGIN_TYPE);
    return true;
  } catch (error) {
    console.error('退出登录失败:', error);
    return false;
  }
};

// 检查是否已登录
export const isLoggedIn = () => {
  return !!getToken() && !!getUserInfo();
};

export default {
  setItem,
  getItem,
  removeItem,
  clearAll,
  setToken,
  getToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  setPoints,
  getPoints,
  setTaskStatus,
  getTaskStatus,
  setLoginType,
  getLoginType,
  saveSearchHistory,
  getSearchHistory,
  clearSearchHistory,
  saveViewedTask,
  getViewedTasks,
  logout,
  isLoggedIn
};